<?php

/**
 * 案件管理
 * @author HelloWorld
 * 2019-8-8
 * UTF-8
 */
class CasecenterController extends Controller_Base
{

    public function init()
    {
        parent::init();
    }

    //操作中心列表
    public function IndexAction()
    {
        $request = $this->getRequest();
        $page = intval($request->getQuery('page', 1));
        $limit = intval($request->getQuery('limit', 10));
        $is_show = intval($request->getQuery('is_show', 0));
        $page = $page ? $page : 1;
        $start = ($page - 1) * $limit;
        $where = $this->getWhere();
        array_push($where, "sysStatus = 1");
        $search = $request->getQuery('search', []);
        if($search){
            foreach ($search as $key => $val){
                if(!empty($val)) {
                    if (strpos($key, 'Time') !== false || strpos($key, 'Date') !== false) {
                        $arr = explode(" 到", $val);
                        $begin = strtotime($arr[0]);
                        $end = strtotime($arr[1]) + 86400;
                        array_push($where, "$key >= $begin AND $key < $end");
                    } elseif (strpos($key, 'start') !== false && is_numeric($val)) {
                        array_push($where, str_replace('start', '', $key) . " >= {$val}");
                    } elseif (strpos($key, 'end') !== false && is_numeric($val)) {
                        array_push($where, str_replace('end', '', $key) . " < {$val}");
                    } elseif(in_array($key,['litigantName','cardId','telephone'])){
                        $caseId = $this->getCaseIdByLitigantName($val,$key);
                        array_push($where,"id in ({$caseId})");
                    } elseif(is_array($val)){
                        $temp = "'".implode("','", $val)."'";
                        array_push($where,"$key in ({$temp})");
                    } elseif($key == 'importRecordId'){
                        array_push($where,"$key in ({$val})");
                    }else {
                        if (is_numeric($val)) {
                            array_push($where, "{$key} = {$val}");
                        } else {
                            array_push($where, "{$key} = '{$val}'");
                        }
                    }
                }
            }
        }
        $query['limit'] = $limit;
        $query['search'] = $search;
        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => $start,
            'order' => 'lastCallTime ASC , `id` ASC'
        );

        $cases = Module_Mediate_Case::getInstance()->getAllBySearch(array("*"), $seacher, true);
        $total = Module_Mediate_Case::getInstance()->getAllBySearch(array("count(*) as num"), array('where' => $where), true);

        $total = $total[0]['num'];
        $totalPage = ceil($total / $limit);


        //赋值调解部门
        $this ->getMediationOrgan();
        //赋值资产方
        $this ->getAssets();
        //赋值调解员
        $this ->getMediator();

        SmartyAdapter::assign('customLabel', Module_Mediate_Case::$customLabel);
        SmartyAdapter::assign('customGrade', Module_Mediate_Case::$customGrade);
        SmartyAdapter::assign('repayStatusArr', Module_Mediate_Case::$repayStatusArr);
        SmartyAdapter::assign('sysStatusArr', Module_Mediate_Case::$sysStatusArr);
        SmartyAdapter::assign('caseStatusArr', Module_Mediate_Case::$caseStatusArr);
        SmartyAdapter::assign('mediateStatus', Module_Mediate_Case::$mediateStatus);
        SmartyAdapter::assign('arrList', $cases);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('is_show', $is_show);
        SmartyAdapter::assign('page_query', http_build_query($query));

    }

    //转交案件
    public function transferCaseAction()
    {
        $request = $this->getRequest();
        //案件id
        $id_str = $request->getPost('transfer_case_ids', '');
        $mediators_id = $request->getPost('mediators_id', '');
        if (!$id_str || empty($mediators_id)) {
            AjaxTool::returnJsonData(4005);
        }

        if (!empty($mediators_id)) {
            $mediator = Module_User_Administrator::getInstance()->getItemById($mediators_id);
            if (!$mediator) {
                AjaxTool::returnJsonData(4001);
            }
        }
        $res = Module_Mediate_Case::getInstance()->saveByIds([
            'mediationOrganId' => $mediator['mediationOrganId'],
            'mediatorId' => $mediator['id'],
            'mediatorName' => $mediator['name'],
            'updateTime' => time(),
            'isTransfer' => 1
        ], $id_str);
        //分配成功，添加日志记录
        if($res){
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $id){
                $data = [
                    'caseId' => $id,
                    'status' => 'case_transfer',
                    'operationUid' => $this->admin['id'],
                    'operationName' => $this->admin['name'],
                    'operationContent' =>"转移案件",
                    'remark' => "将案件转交给调解员{$mediator['name']},调解员id为：{$mediator['id']}",
                    'createTime' => time(),
                ];
                $post_data = [
                    'type' => 'Module_Task_Case',
                    'method' => 'addOperateLog',
                    'data' => $data
                ];
                @Module_Queue_Base::addQueue($post_data);
            }

        }
        AjaxTool::returnJsonData(200, '成功转交' . $res . '件案件');

    }

    //撤案
    public function withdrawAction()
    {
        $request = $this->getRequest();
        $case_ids = $request->getPost('withdraw_case_ids', '');
        if (empty($case_ids)) {
            AjaxTool::returnJsonData(4001);
        }
        $res = Module_Mediate_Case::getInstance()->saveByIds([
            'sysStatus' => 2,
            'updateTime' => time()
        ], $case_ids);
        //分配成功，添加日志记录
        if($res){
            $id_arr = explode(',', $case_ids);
            foreach ($id_arr as $id){
                $data = [
                    'caseId' => $id,
                    'status' => 'case_withdraw',
                    'operationUid' => $this->admin['id'],
                    'operationName' => $this->admin['name'],
                    'operationContent' =>"撤案",
                    'remark' => ",",
                    'createTime' => time(),
                ];
                $post_data = [
                    'type' => 'Module_Task_Case',
                    'method' => 'addOperateLog',
                    'data' => $data
                ];
                @Module_Queue_Base::addQueue($post_data);
            }

        }
        AjaxTool::returnJsonData(200);
    }

    //更改委案到期时间
    public function entrustExpireTimeAction()
    {
        $request = $this->getRequest();
        $case_ids = $request->getPost('entrustExpireTime_case_ids', '');

        $entrustExpireTime = $request->getPost('delayTime', '');

        if (empty($case_ids) || empty($entrustExpireTime)) {
            AjaxTool::returnJsonData(4001);
        }

        $id_arr = explode(",", $case_ids);

        if (count($id_arr) <= 1) {
            foreach ($id_arr as $case_id) {
                $case = Module_Mediate_Case::getInstance()->getItemById($case_id);
                $updataCase = [
                    'entrustExpireTime' => strtotime($entrustExpireTime) + 86400 - 1,//精确到当天的24点
                    'id' => $case_id,
                ];
                $log = [
                    'caseId' => $case['id'],
                    'status' => 'update_expire_time',
                    'operationUid' => $this->admin['id'],
                    'operationName' => $this->admin['name'],
                    'operationContent' => '更新委案到期时间',
                    'remark' => '从' . date("Y-m-d H:i:s", $case['entrustExpireTime']) . '更新为' . $entrustExpireTime,
                    'createTime' => time(),
                ];

                $res = Module_Mediate_Case::getInstance()->updateStatusAddLogById($updataCase, $log);
                if (!$res) {
                    Func_Log::write('entrustExpireTime', 'case save error', '$updataCase= ' . json_encode($updataCase) . ',$log=' . json_encode($log));
                }
            }
        } else {
            $case = [];
            $case['operationUid'] = $this->admin['id'];
            $case['operationName'] = $this->admin['name'];
            $case['case_id_str'] = $case_ids;
            $case['entrustExpireTime'] = strtotime($entrustExpireTime) + 86400 - 1;//精确到当天的24点

            $post_data = array(
                'type' => 'Module_Task_Casecenter',
                'method' => 'entrustExpireTime',
                'data' => $case
            );
            @Module_Queue_Base::addQueue($post_data);
        }
        AjaxTool::returnJsonData(200);
    }

    //导出调解记录
    public function exportMediateRecordAction(){
        $request = $this->getRequest();
        $fileType = $request->getPost('fileType', '');
        //案件id
        $id_str = $request->getPost('export_case_ids', '');
        $callTime = $request->getPost('callTime', '');
        if(empty($id_str)){
            AjaxTool::returnJsonData('301',"缺少必要参数");
        }
        $where = [];
        if($callTime){
            $arr = explode(" 到", $callTime);
            if($arr) {
                $begin = strtotime($arr[0]);
                $end = strtotime($arr[1]) + 86400;
                array_push($where, "addTime >= $begin AND addTime < $end");
            }
        }
        $res = Module_Mediate_ExportData::getInstance()->singleInsert([
            'fileType'=> $fileType,
            'exportType'=> 1,
            'mediationOrganId'=> $this->admin['mediationOrganId'],
            'mediatorId'=> $this->admin['id'],
            'mediatorName'=> $this->admin['name'],
            'addTime'=> time(),
            'initialData'=> $id_str,
            'exportWhere'=> json_encode($where),
        ]);
        if(!$res){
            AjaxTool::returnJsonData(400,'提交失败');
        }
        AjaxTool::returnJsonData(200,'提交成功');

    }
    //导出短信记录
    public function exportSmsRecordAction(){
        $request = $this->getRequest();
        $fileType = $request->getPost('fileType', '');
        //案件id
        $id_str = $request->getPost('export_case_ids', '');
        $sendTime= $request->getPost('sendTime', '');
        if(empty($id_str)){
            AjaxTool::returnJsonData('301',"缺少必要参数");
        }
        $where = [];
        if($sendTime){
            $arr = explode(" 到", $sendTime);
            $begin = strtotime($arr[0]);
            $end = strtotime($arr[1]) + 86400;
            array_push($where, "sendTime >= $begin AND sendTime < $end");
        }
        $res = Module_Mediate_ExportData::getInstance()->singleInsert([
            'fileType'=> $fileType,
            'exportType'=> 4,
            'mediationOrganId'=> $this->admin['mediationOrganId'],
            'mediatorId'=> $this->admin['id'],
            'mediatorName'=> $this->admin['name'],
            'addTime'=> time(),
            'initialData'=> $id_str,
            'exportWhere'=> json_encode($where),
        ]);
        if(!$res){
            AjaxTool::returnJsonData(400,'提交失败');
        }
        AjaxTool::returnJsonData(200,'提交成功');

    }
    //导出呼叫记录
    public function exportCallRecordAction(){
        $request = $this->getRequest();
        $fileType = $request->getPost('fileType', '');
        //案件id
        $id_str = $request->getPost('exportCall_case_ids', '');
        $callTime = $request->getPost('callTime', '');

        if(empty($id_str)){
            AjaxTool::returnJsonData('301',"缺少必要参数");
        }
        $where = [];
        if($callTime){
            $arr = explode(" 到", $callTime);
            $begin = strtotime($arr[0]);
            $end = strtotime($arr[1]) + 86400;
            array_push($where, "callTime >= $begin AND callTime < $end");
        }
        $res = Module_Mediate_ExportData::getInstance()->singleInsert([
            'fileType'=> $fileType,
            'exportType'=> 3,
            'mediationOrganId'=> $this->admin['mediationOrganId'],
            'mediatorId'=> $this->admin['id'],
            'mediatorName'=> $this->admin['name'],
            'addTime'=> time(),
            'initialData'=> $id_str,
            'exportWhere'=> json_encode($where),

        ]);
        if(!$res){
            AjaxTool::returnJsonData(400,'提交失败');
        }
        AjaxTool::returnJsonData(200,'提交成功');

    }

    //导出调解录音
    public function exportFileRecordAction(){
        $request = $this->getRequest();
        $fileType = $request->getPost('fileType', '');
        $callTime = $request->getPost('callTime', '');
        if(empty($fileType)){
            AjaxTool::returnJsonData('301',"请选择录音文件格式");
        }
        $where = [];
        if($callTime){
            $arr = explode(" 到", $callTime);
            $begin = strtotime($arr[0]);
            $end = strtotime($arr[1]) + 86400;
            array_push($where, "callTime >= $begin AND callTime < $end");
        }
        //案件id
        $id_str = $request->getPost('exportFile_case_ids', '');
        if(empty($id_str)){
            AjaxTool::returnJsonData('301',"缺少必要参数");
        }
        $res = Module_Mediate_ExportData::getInstance()->singleInsert([
            'fileType'=> $fileType,
            'exportType'=> 2,
            'mediationOrganId'=> $this->admin['mediationOrganId'],
            'mediatorId'=> $this->admin['id'],
            'mediatorName'=> $this->admin['name'],
            'addTime'=> time(),
            'initialData'=> $id_str,
            'exportWhere'=> json_encode($where),

        ]);
        if(!$res){
            AjaxTool::returnJsonData(400,'提交失败');
        }
        AjaxTool::returnJsonData(200,'提交成功');
    }

}

